package com.gtw.interpreter;

import java.util.HashMap;
import java.util.Stack;

public class Context {
    //定义表达式
    private Expression expression;

    /**
     * 定义一个具体的语法容器,容纳一个具体的表达式
     */
    private Stack<Expression> stack = new Stack<Expression>();

    public Context(String expStr) {
        //拆分表达式为字符数组
        char[] charArray = expStr.toCharArray();
        //运算
        Expression left = null;
        Expression right = null;
        for(int i = 0 ; i < charArray.length ; i++){
            switch (charArray[i]){
                case '+'://加法
                    left = stack.pop();
                    right = new TerminalExpression(String.valueOf(charArray[++i]));
                    stack.push(new AddExpression(left, right));
                    break;
                case '-':
                    left = stack.pop();
                    right = new TerminalExpression(String.valueOf(charArray[++i]));
                    stack.push(new SubExpression(left, right));
                    break;
                default:
                    stack.push(new TerminalExpression(String.valueOf(charArray[i])));
            }
        }
        this.expression = stack.pop();

    }

    public int run(HashMap<String, Integer> var){

        return this.expression.interpret(var);
    }
}
